// cj-impl-shim.js
// 一个用于替代/模拟 "真实仓颉实现" 的轻量 Node.js shim，提供与 Node 参考实现相同的 HTTP 接口。
// 目的：当本地仓颉运行时无法直接提供 HTTP 功能时，使用此 shim 立即生成可比数据。

const http = require('http');

const PORT = 3000;

function nowISO() {
  return new Date().toISOString();
}

function sendJSON(res, obj, status = 200) {
  const body = JSON.stringify(obj);
  res.writeHead(status, {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(body),
  });
  res.end(body);
}

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/api/hello') {
    sendJSON(res, { message: 'hello world' });
    return;
  }

  if (req.method === 'GET' && req.url === '/api/time') {
    sendJSON(res, { now: nowISO(), uptime: process.uptime() });
    return;
  }

  if (req.method === 'POST' && req.url === '/api/echo') {
    let body = '';
    req.on('data', (chunk) => { body += chunk; });
    req.on('end', () => {
      try {
        const obj = JSON.parse(body || '{}');
        sendJSON(res, obj);
      } catch (e) {
        sendJSON(res, { error: 'invalid json' }, 400);
      }
    });
    return;
  }

  // root
  if (req.method === 'GET' && req.url === '/') {
    const html = '<html><body><h1>CJ Shim</h1><ul><li><a href="/api/hello">/api/hello</a></li><li><a href="/api/time">/api/time</a></li></ul></body></html>';
    res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(html) });
    res.end(html);
    return;
  }

  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('not found');
});

server.listen(PORT, () => {
  console.log('CJ shim listening on port', PORT);
});

// graceful shutdown
process.on('SIGINT', () => { server.close(() => process.exit(0)); });
process.on('SIGTERM', () => { server.close(() => process.exit(0)); });
